const { createServer, Model } = require("miragejs")
const _ = require('lodash')

let users = []
let tokens = []

let tokenID = _.uniqueId('token_')
users.push({token: tokenID, name: "admin", roles: ['admin'], introduction: 'I am a super administrator', avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'})
tokens.push({username: 'admin', token: tokenID})

tokenID = _.uniqueId('token_')
users.push({token: tokenID, name: "editor", roles: ['editor'], introduction: 'I am an editor', avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif' })
tokens.push({username: 'editor', token: tokenID})

tokenID = _.uniqueId('token_')
users.push({token: tokenID, name: "rocky", roles: ['editor'], introduction: 'I am an Rocky', avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif' })
tokens.push({username: 'rocky', token: tokenID})

let createUsers = createServer({
    models: {
      users: Model,
      tokens: Model,
    },
    routes() {
      this.namespace = "api"

      this.post("/user/login", (schema, request) => {
        const { username } = JSON.parse(request.requestBody)
        const token = schema.tokens.findBy({ username: username })
  
        if (!token) {
            return {
                code: 60204,
                message: 'Account and password are incorrect.'
            }
        }

        return {
            code: 20000,
            data: token
        }
      })

      this.get("/user/get", (schema, request) => {
        const { token } = request.queryParams
        const info = schema.users.findBy({ token: token })
  
        // mock error
        if (!info) {
          return {
            code: 50008,
            message: 'Login failed, unable to get user details.'
          }
        }
  
        return {
          code: 20000,
          data: info
        }
      })
    },

    seeds(server) {
        server.db.loadData({
          users: users,
          tokens: tokens
        })
    }
  })


module.exports = createUsers